package com.zjeav.lingjiao.ui.home;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dalimao.corelibrary.view.HorizontalListView;
import com.jpeng.jptabbar.JPTabBar;
import com.maning.mndialoglibrary.MProgressDialog;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.bean.ZxingConfig;
import com.yzq.zxinglibrary.common.Constant;
import com.zjeav.lingjiao.R;
import com.zjeav.lingjiao.base.adapter.BookAdapter;
import com.zjeav.lingjiao.base.adapter.HorizontalAdapter;
import com.zjeav.lingjiao.base.baseBean.Book;
import com.zjeav.lingjiao.base.baseBean.Province;
import com.zjeav.lingjiao.base.request.MallBookRequest;
import com.zjeav.lingjiao.base.response.BannerResponse;
import com.zjeav.lingjiao.base.response.SubjectResponse;
import com.zjeav.lingjiao.base.tools.GlideImageLoader;
import com.zjeav.lingjiao.base.utils.ErrorUtils;
import com.zjeav.lingjiao.ui.book.BookDetialActivity;
import com.zjeav.lingjiao.ui.book.BookMarketActivity;
import com.zjeav.lingjiao.ui.book.MallBookContract;
import com.zjeav.lingjiao.ui.book.SaoMiaoBookActivity;
import com.zjeav.lingjiao.ui.book.WebViewShowActivity;
import com.zjeav.lingjiao.ui.home.persenter.MainPersenter;
import com.zjeav.lingjiao.ui.home.view.BookMarkContract;
import com.zjeav.lingjiao.ui.presenter.BookPresenter;

import java.util.ArrayList;
import java.util.Arrays;

import static android.app.Activity.RESULT_OK;

/**
 * Created by jpeng on 16-11-14.
 */
public class BookMarkFragment extends Fragment implements BookMarkContract.View, View.OnClickListener,
        MallBookContract.View {

    private JPTabBar mTabBar;
    ImageView saomiao_img;
    private int REQUEST_CODE_SCAN = 111;
    Integer[] images = {R.mipmap.banner, R.mipmap.zhuanchang};
    private MainPersenter mainPersenter;
    RecyclerView recyclerView, extracurricular_rv;
    BookAdapter hot_adapter, extra_adapter;
    ArrayList<Book> hotBooks = new ArrayList<>();
    ArrayList<Book> ExtraBooks = new ArrayList<>();
    Banner banner;
    BookPresenter bookPresenter;
    private HorizontalListView mHorizontalListView;
    private HorizontalAdapter mAdapter;
    ArrayList<SubjectResponse> subjects = new ArrayList<>();
    ArrayList<BannerResponse> bannerResponses = new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View layout = inflater.inflate(R.layout.bookmark, null);
        init(layout);
        return layout;
    }

    @Override
    public void onResume() {
        super.onResume();
        hotBooks.clear();
        ExtraBooks.clear();
        mainPersenter.getHotBooks();
        mainPersenter.getExtraBooks();
        mainPersenter.getMarketBanner();
    }


    private void init(View layout) {
        mTabBar = ((RestructureMainActivity) getActivity()).getTabbar();
        banner = layout.findViewById(R.id.banner);
        recyclerView = layout.findViewById(R.id.recyclerView);
        extracurricular_rv = layout.findViewById(R.id.extracurricular_rv);
        saomiao_img = layout.findViewById(R.id.saomiao_img);
        saomiao_img.setOnClickListener(this);
        hot_adapter = new BookAdapter(getContext(), 1);
        extra_adapter = new BookAdapter(getContext(), 1);
        recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3));
        extracurricular_rv.setLayoutManager(new GridLayoutManager(getContext(), 3));
        recyclerView.setAdapter(hot_adapter);
        extracurricular_rv.setAdapter(extra_adapter);
        mainPersenter = new MainPersenter(this);
//        Banner banner = layout.findViewById(R.id.banner);
//        banner.setImages(Arrays.asList(images)).setImageLoader(new GlideImageLoader()).start();

        mHorizontalListView = (HorizontalListView) layout.findViewById(R.id.bookhlv);
        bookPresenter = new BookPresenter(this);
        bookPresenter.getFiltrateBooks(new MallBookRequest(1, 10, String.valueOf(1)));
        bookPresenter.getSubjects();

        mAdapter = new HorizontalAdapter(subjects, getActivity());
        mHorizontalListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                SubjectResponse subjectResponse = (SubjectResponse) adapterView.getItemAtPosition(i);
                Intent intent = new Intent(getContext(), BookMarketActivity.class);
                intent.putExtra("subjectid", subjectResponse.getId());
                intent.putExtra("name",subjectResponse.getName());
                startActivity(intent);
            }
        });

        hot_adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Book book = (Book) adapter.getItem(position);

                Intent intent = new Intent(getContext(), BookDetialActivity.class);
                intent.putExtra("id", book.getId());
                intent.putExtra("isbuy", true);
                startActivity(intent);
            }
        });
        extra_adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Book book = (Book) adapter.getItem(position);

                Intent intent = new Intent(getContext(), BookDetialActivity.class);
                intent.putExtra("id", book.getId());
                intent.putExtra("isbuy", true);
                startActivity(intent);
            }
        });


    }

    @Override
    public void showHotBooks(ArrayList<Book> books) {
        this.hotBooks.addAll(books);
        hot_adapter.replaceData(this.hotBooks);
    }

    @Override
    public void showExtraBooks(ArrayList<Book> books) {
        this.ExtraBooks.addAll(books);
        extra_adapter.replaceData(this.ExtraBooks);
    }

    @Override
    public void showMallBanners(ArrayList<BannerResponse> list) {
        int size = list.size();
        bannerResponses.clear();
        bannerResponses.addAll(list);
        String[] images = new String[size];
        for (int i = 0; i < list.size(); i++) {
            images[i] = list.get(i).getImg();
        }
        banner.setImages(Arrays.asList(images)).setImageLoader(new GlideImageLoader()).start();
        //设置点击事件，下标是从0开始
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                if (bannerResponses.get(position).getType().equals("book")) {
                    Intent intent = new Intent(getContext(), BookDetialActivity.class);
                    intent.putExtra("id", bannerResponses.get(position).getMetadata().getId());
                    getContext().startActivity(intent);
                } else if (bannerResponses.get(position).getType().equals("h5")) {
                    if (!bannerResponses.get(position).getMetadata().getUrl().equals("")) {
                        Intent intent = new Intent(getContext(), WebViewShowActivity.class);
                        intent.putExtra("url", bannerResponses.get(position).getMetadata().getUrl());
                        getContext().startActivity(intent);
                    }
                } else {
                    Intent intent = new Intent(getContext(), BookMarketActivity.class);
                    intent.putExtra("cateid", bannerResponses.get(position).getMetadata().getId());
                    getContext().startActivity(intent);
                }
            }
        });
    }

    @Override
    public void ShowError(Throwable throwable) {
        Toast.makeText(getContext(), ErrorUtils.showError(throwable), Toast.LENGTH_SHORT).show();
        if (MProgressDialog.isShowing()) {
            MProgressDialog.dismissProgress();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.saomiao_img:
                saoMiao();
                break;
            default:
                break;
        }
    }

    private void saoMiao() {
        Intent intent = new Intent(getActivity(), CaptureActivity.class);

        /*ZxingConfig是配置类
         *可以设置是否显示底部布局，闪光灯，相册，
         * 是否播放提示音  震动
         * 设置扫描框颜色等
         * 也可以不传这个参数
         * */
        ZxingConfig config = new ZxingConfig();
        config.setPlayBeep(true);//是否播放扫描声音 默认为true
        config.setShake(true);//是否震动  默认为true
        intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
        startActivityForResult(intent, REQUEST_CODE_SCAN);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                String content = data.getStringExtra(Constant.CODED_CONTENT);
                Intent intent = new Intent(getContext(), SaoMiaoBookActivity.class);
                intent.putExtra("content", content);
                startActivity(intent);
            }
        }
    }

    @Override
    public void showMallBooks(ArrayList<Book> list) {

    }

    @Override
    public void getGrades(ArrayList<SubjectResponse> list) {

    }

    @Override
    public void getSubjects(ArrayList<SubjectResponse> list) {
        subjects.clear();
        subjects.addAll(list);
        mHorizontalListView.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void showError(Throwable throwable) {
        Toast.makeText(getActivity(), ErrorUtils.showError(throwable), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showRegions(ArrayList<Province> province) {

    }


}
